import axios from 'axios'
import { ShowLoading, ShowError } from '../utils/message'
import { closeToast } from 'vant'
import { useUserStore } from '../store/user'

export const baseURL = 'http://cba.itlike.com/public/index.php?s=/api/'

const request = axios.create({
    baseURL: baseURL,
    headers: {},
    timeout: 8000,
})

request.interceptors.request.use(function (config: any) {
    const { token } = useUserStore()

    config.headers.platform = 'h5';
    config.headers['Access-Token'] = token;
    ShowLoading()
    return config;
}, function (error) {
    ShowError('请求失败')
    return Promise.reject(error)
})

request.interceptors.response.use(function (response: any) {
    closeToast()
    console.log(response.data);
    return response.data

}, function (error) {
    ShowError('响应失败')
    return Promise.reject(error)
})

export const toGet = async (url: string, params?: any, headers?: any) => {
    return new Promise((resolve, reject) => {
        request({
            url,
            method: "GET",
            params: params,
            headers: headers,
        })
            .then(res => {
                resolve(res)    // 成功
            })
            .catch(err => {
                reject(err)     // 失败
            })
    })
}

export const toPost = async (url: string, data?: any, params?: any, headers?: any) => {
    return new Promise((resolve, reject) => {
        request({
            url,
            method: "POST",
            data: data,
            params: params,
            headers: headers,
        })
            .then(res => {
                resolve(res)    // 成功
            })
            .catch(err => {
                reject(err)     // 失败
            })
    })
}

export default request